<template>
  <div>
    <el-form :model="form">
    <!-- 2.v-model 绑定表单 -->

    <el-form-item label="一级分类" label-width="120px" :rules="[
      { required: true}]">
        <el-select v-model="form.first_cateid" placeholder="请选择一级分类" @change="changeFirstCateId">
            <!--6.遍历分类数据  -->
            <el-option
                v-for="item in cate_Arr"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
                ></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="二级分类" label-width="120px" :rules="[
      { required: true}]">
        <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
            <!--9.遍历secondCateList  -->
            <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
                ></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="商品名称" label-width="120px" :rules="[
      { required: true}]">
        <el-input v-model="form.goodsname" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="价格" label-width="120px">
        <el-input v-model="form.price" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="市场价格" label-width="120px">
        <el-input v-model="form.market_price" autocomplete="off"></el-input>
    </el-form-item>
    form:{{form}}
    <el-form-item label="图片" label-width="120px">
        <div class="avant">
            <h3 class="plus">+</h3>

            <input class="ipt" type="file" @change="changeImg" />
            <img class="img" v-if="imgUrl" :src="imgUrl" alt />
        </div>
    </el-form-item>
    <el-form-item label="商品规格" label-width="120px">
        <el-select v-model="form.specsid" placeholder="请选择商品规格" @change="changeSpecsId">
            <!--13.遍历specsList  -->
            <el-option
                v-for="item in specs_Arr"
                :key="item.id"
                :label="item.specsname"
                :value="item.id"
                ></el-option>
            </el-select>
    </el-form-item>
    <el-form-item label="规格属性" label-width="120px">
        <el-select v-model="form.specsattr" placeholder="请选择规格属性" multiple>
            <!--遍历arr  -->
            <el-option v-for="item in arr" :key="item" :label="item" :value="item"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="是否新品" label-width="120px">
        <el-radio v-model="form.isnew" :label="1">是</el-radio>
        <el-radio v-model="form.isnew" :label="2">否</el-radio>
    </el-form-item>
    <el-form-item label="是否热卖" label-width="120px">
        <el-radio v-model="form.ishot" :label="1">是</el-radio>
        <el-radio v-model="form.ishot" :label="2">否</el-radio>
    </el-form-item>

    <el-form-item label="状态" label-width="120px">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
    </el-form-item>
    <el-form-item label="商品描述" label-width="120px">
        <div id="editor"></div>
    </el-form-item>

    <el-form-item label-width="120px">
          <el-button type="primary" @click="commit">{{$route.path == '/goods/add'? '添加':'修改'}}</el-button>
        </el-form-item>
</el-form>
      
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import {reqgoodsadd,reqgoodsedit,reqgoodsinfo} from '../../../http/api';
import { successAlert,errorAlert } from '../../../utils/alert';
import path from 'path';
import E from "wangeditor";
export default {
  computed: {
    ...mapGetters({
      cate_Arr:'cate/cate_Arr',
      specs_Arr:'specs/specs_Arr'
    })
  },
  data() {
    return {
        form:{
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 1
      },
      secondCateList:[],
      arr:[],
      imgUrl :""
    }
  },
  mounted(){
    // 生成富文本编辑器
    this.editor = new E("#editor");
    this.editor.create();
  },
  activated() {
    this.set_cateArr({istree:true});
    this.set_specsArr();
    if(this.$route.path !== "/goods/add"){
      // console.log(this.$route);
      reqgoodsinfo({ id:this.$route.params.id }).then((res) => {
            if (res.data.code === 200) {
                this.form = res.data.list;
                
                this.getSecondCateList();
                this.imgUrl = this.$pre + this.form.img;
                
                
                if(this.form.specsattr.indexOf('[')!=-1){
                  this.form.specsattr = JSON.parse(this.form.specsattr);
                }else{
                  this.form.specsattr = this.form.specsattr.split(',');
                }
                this.getSpecsId();

                this.editor.txt.html(this.form.description);
            }
        }).catch((err) => {
            console.log('请求失败-----err:' + err);
        })
    };
  },
  beforeRouteLeave(to,from,next){
    // console.log(to,from);
    if(from.path !== '/goods/add'){
        this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 1
      };
    };
    this.secondCateList = []; this.arr = []; this.imgUrl = "";
    this.editor.txt.html('');
    next()
    },
  
  methods: {
    ...mapActions({
      set_specsArr:'specs/set_specsArr',
      set_cateArr:'cate/set_cateArr'
    }),
   commit(){
      this.form.description = this.editor.txt.html();
      this.form.specsattr = JSON.stringify(this.form.specsattr);
      if(this.$route.path === '/goods/add'){
        reqgoodsadd(this.form).then(res => {
          if(res.data.code===200){
          //弹成功
          successAlert(res.data.msg);
          this.form = {
            first_cateid: "",
            second_cateid: "",
            goodsname: "",
            price: "",
            market_price: "",
            img: null,
            description: "",
            specsid: "",
            specsattr: [],
            isnew: 2,
            ishot: 2,
            status: 1
          };
          this.secondCateList = []; 
          this.arr = []; 
          this.imgUrl = "";
          this.editor.txt.html('');
          //返回菜单管理
          this.$router.push('/goods');
        }
      })
     }else{
       this.form.id = this.$route.params.id;
       reqgoodsedit(this.form).then(res => {
        if(res.data.code===200){
          //弹成功
          successAlert(res.data.msg);
          //返回菜单管理
          this.$router.push('/goods');
        }
      })
     }
   },
   changeFirstCateId(){
      this.form.second_cateid = "";
      this.getSecondCateList();
   },
   getSecondCateList(){
     let obj = this.cate_Arr.find(item=>{
       return item.id == this.form.first_cateid
     });
     this.secondCateList = obj ? obj.children : [];
   },
   changeSpecsId(){
      this.form.specsattr = [];
      this.getSpecsId();
   },
   getSpecsId(){
     let obj = this.specs_Arr.find(item=>(item.id == this.form.specsid));
     this.arr = obj?obj.attrs:[];
   },
   changeImg(e){
        let file = e.target.files[0];

        // 验证文件大小
        if(file.size > 2*1024*1024){
            errorAlert('上传文件不能超过2M');
            return
        }

        // 验证文件类型
        let extname = path.extname(file.name);
        console.log(extname);
        let imgExtnames = ['.jpeg','.jpg','.png','.gif'];

        if(!imgExtnames.includes(extname)){
            errorAlert('请上传正确的文件格式');
            return
        }
        this.imgUrl = URL.createObjectURL(file);

        this.form.img = file;
    },
  }
};
</script>
<style scoped lang="less">
@import url('../../../less/index.less');
.avant{
    width: 80px;
    height: 80px;
    border: 1px dashed @bg-deep;
    border-radius: @padding10;
    text-align: center;
    line-height: 45px;
    position: relative;
    overflow: hidden;
    input[type='file']{
        width: 100%;
        height: 100%;
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 10;
    }
    img{
        width: 100%;
        height: 100%;
        opacity: 1;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
    }
}
</style>